<script lang="ts" setup>
import type { DataType } from './types';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { Page,VbenButton } from '@vben/common-ui';
import { Button, message, Popconfirm, Space ,Image,Modal} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deletePage_news, getPage_news ,update_sort,deleteMultiple} from '#/api/portal/vechiledetail';
import Icon from '#/components/Icons';
import { formatImagesList, queryStringToObject} from '#/utils';
import { getPage_news as car_model } from '#/api/portal/carmodel';
import {
  getArticleSelectCategorys,
} from '#/api/portal/article';
defineOptions({
  name: 'PortalAdminPage',
});
const categoriesTree = ref([]);
const route = useRoute();
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
const code = ref('');
const carOptions = ref([]); // ✅ 外部定义，响应式


const modalVisible = ref(false); // 控制 Modal 显示
const selectedRows = ref<DataType[]>([]); // 存放选中的行
const onCheckboxChange = ({ records }) => {
  console.log(records)
  selectedRows.value = records;
};


onMounted(async () => {
  const { data: { list }} = await getArticleSelectCategorys({ code: 'product' });
  categoriesTree.value=list;


})


const gridOptions: VxeGridProps<DataType> = {
   checkboxConfig:{
    range: true, // 可选：支持 shift 连选
   
  },
  rowConfig: {
    isCurrent: true,
    isHover: true,
     drag: true,
  },
  columns: [
    { field: 'id', title: '编号', dragSort: true ,type:'checkbox'},
    { field: 'carModel.category.name', title: '类型' },
    { field: 'carModel.name', title: '车型' },
    { field: 'name', title: '特征' },
    { field: 'images', title: '图片',slots:{default:'image'} },
    {
        field: 'update_time',
        sortable: true,
        title: '更新时间',
    },
    {
        slots: { default: 'action' },
        field: 'action',
        fixed: 'right',
        title: '操作',
        width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    layouts: ['Total', 'Sizes', 'PrevPage', 'Number', 'NextPage', 'FullJump'], // 带总条数和每页大小选择
    pageSize: 10,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const param = queryStringToObject(route.meta.param as string);
        if (param?.code) {
          formValues.code = param.code;
          code.value = param.code;
        }

        const { data } = await getPage_news({
          page: page.currentPage,
          limit: page.pageSize,
          ...formValues,
        });
        const total = data.list.length;
      
        data.list = formatImagesList(data.list, 'images');
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
// const onSearchNews = async (value) => {

//  const res = await car_model({page:1,limit:10,keyword:value});

//   carOptions.value = (res?.data?.list || []).map(item => ({
//     label: item.category_name+' '+ item.name,
//     value: item.id,
//   }))

// }
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
 
    {
      component: 'Input',
      componentProps: {
        placeholder: `请输入${viewTitle}`,
      },
      fieldName: 'keyword',
      label: `${viewTitle}名称:`,
    },
     {
      component: 'TreeSelect',
      componentProps: {
        treeData: categoriesTree,
        multiple: true, // ✅ 启用多选
        fieldNames: {
          value: 'id',
          key: 'id',
          label: 'name',
          children: 'children',
        },
        placeholder: `请选择${viewTitle}分类`, // 可选，增强体验
        allowClear: true, // 可选，添加清除按钮
      },
      fieldName: 'category_id',
      label: `${viewTitle}分类`,
    },

    {
        component: 'Select',
        fieldName: 'car_model',
        label: `${viewTitle}车型`,
        componentProps: {
            class: 'w-full',
            placeholder: '选择车型',
            options: carOptions,
            allowClear: false,
            showSearch: false,
            mode:'multiple',
            filterOption: false, // 不使用本地过滤
            // onSearch: onSearchNews, // ✅ 绑定搜索触发事件
        },
        dependencies: {
            trigger:async  (values, formModel) => {
               values.car_model = [];
                  
              if (!values.category_id) {
                carOptions.value = [];
                return;
              }
              const res =  await  car_model({page:1,limit:10,category_id:values.category_id});
              carOptions.value = (res?.data?.list || []).map(item => ({
                label: item.category_name+' '+ item.name,
                value: item.id,
              }))
  
            },
            triggerFields: ['category_id'],
       },
      
      },  

  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
};
const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});




const gridEvents: VxeGridListeners<AddDataType> = {
  async rowDragend() {
    const visibleData = GridApi.grid.getTableData().visibleData;
    const result: { [key: string]: number } = {};
    // 使用 forEach 替代 reduce
    visibleData.forEach((item, index) => {
      result[item.id] = index;
    });

  await update_sort({ list_orders: result });
  },
};


const handleDelete = async (row: DataType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deletePage_news(row.id);
    $table.remove(row);
    message.success(msg);
  }
};

const openDialog = async (row?: DataType) => {
  const id = row?.id || 0;
console.log('可用路由:', router.getRoutes());

  router.push({
    name: `PortalvechiledetailDetail`,
    params: { id },
  });
};


  const openDeleteConfirm = () => {

  const $table = GridApi.grid;
    const selectedRows = $table.getCheckboxRecords();
    console.log(selectedRows)
  if (selectedRows.length === 0) {
    message.warning('请先选择需要删除的项');
    return;
  }

  Modal.confirm({
    title: '确认删除',
    content: `你确定要删除选中的 ${selectedRows.length} 项吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      const ids = selectedRows.map(item => item.id);
      try {
        const { msg } = await deleteMultiple(ids); // ❗️这里是你定义的 API，传数组 ID
        const $table = GridApi.grid;
        message.success(msg || '删除成功');
        $table.commitProxy('query'); // ✅ 删除成功后刷新表格数据
      } catch (err) {
        message.error('删除失败，请稍后重试');
      }
    },
  });

  
};


</script>

<template>
  <Page auto-content-height>
    <Grid :grid-events="gridEvents" :table-title="`${viewTitle}列表`">
      
      <template #image="{ row }">
        <Image
          v-if="Array.isArray(row.images) && row.images.length > 0 && row.images[0].url"
          :src="row.images[0].url"
          :height="30"
          :width="30"
        />
      </template>
      <template #toolbar-tools>
         <VbenButton @click="openDeleteConfirm()" class="mr-2">选中删除</VbenButton>
          <Modal v-model:visible="modalVisible" title="确认删除" class="w-[600px]">
            <template #default>
              <p>你确定要删除选中的 {{ selectedRows.length }} 项吗？此操作无法恢复。</p>
            </template>
            <template #footer>
              <VbenButton @click="modalVisible = false">取消</VbenButton>
              <VbenButton type="primary" danger @click="openDeleteConfirm()">确认删除</VbenButton>
            </template>
          </Modal>
        <Button class="mr-2" type="primary" @click="openDialog()">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          新增{{ viewTitle }}
        </Button>
      </template>

      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="openDialog(row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            编辑
          </Button>
          <Popconfirm
            cancel-text="否"
            ok-text="是"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <Button danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              删除
            </Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
